// 程序入口（加载 DSL → 构建系统）

import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';
import { DSLParser } from './dsl/parser';
import { DomainGraph } from './runtime/domainGraph';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

/**
 * 最小 Demo：从 DSL → 自动生成对象图
 */
async function main() {
  console.log('🚀 启动 TypeScript DSL ORM Demo');
  console.log('================================');

  try {
    // 1. 读取 YAML DSL 文件
    const modelsDir = path.join(__dirname, '../models');
    const yamlFiles = [
      { name: 'user.yml', path: path.join(modelsDir, 'user.yml') },
      { name: 'order.yml', path: path.join(modelsDir, 'order.yml') }
    ];

    console.log('📁 读取 DSL 文件...');
    const yamlContents = yamlFiles.map(file => ({
      name: file.name,
      content: fs.readFileSync(file.path, 'utf-8')
    }));

    console.log(`✅ 成功读取 ${yamlContents.length} 个 DSL 文件`);

    // 2. 解析 YAML 并生成 Domain Graph
    console.log('\n🔄 解析 DSL 并构建 Domain Graph...');
    const domainGraph = await DSLParser.parseMultipleYAML(yamlContents);

    // 3. 展示 Domain Graph 信息
    console.log('\n📊 Domain Graph 统计信息:');
    const stats = domainGraph.getStatistics();
    console.log(`  - 节点数量: ${stats.nodeCount}`);
    console.log(`  - 连接数量: ${stats.connectionCount}`);
    console.log(`  - 平均连接数: ${stats.averageConnections.toFixed(2)}`);
    console.log(`  - 最大深度: ${stats.maxDepth}`);

    // 4. 展示所有节点
    console.log('\n🏗️  领域实体:');
    const nodes = domainGraph.getAllNodes();
    nodes.forEach(node => {
      console.log(`  - ${node.name} (${node.type})`);
      console.log(`    主键: ${node.definition.identity}`);
      console.log(`    属性: ${Object.keys(node.definition.attributes).join(', ')}`);
      
      if (node.definition.associations && Object.keys(node.definition.associations).length > 0) {
        console.log(`    关联: ${Object.keys(node.definition.associations).join(', ')}`);
      }
      
      const connections = domainGraph.getConnections(node.id);
      if (connections.length > 0) {
        console.log(`    连接数: ${connections.length}`);
      }
      console.log('');
    });

    // 5. 展示关系图
    console.log('🔗 实体关系:');
    nodes.forEach(node => {
      const connections = domainGraph.getConnections(node.id);
      connections.forEach(conn => {
        const targetNode = domainGraph.getNode(conn.targetId);
        if (targetNode) {
          console.log(`  ${node.name} --[${conn.relationship.type}]--> ${targetNode.name}`);
        }
      });
    });

    // 6. 演示图遍历
    if (nodes.length > 0) {
      console.log('\n🚶 图遍历演示:');
      const startNode = nodes[0];
      console.log(`从 ${startNode.name} 开始遍历...`);
      
      const traversalResult = domainGraph.traverse(startNode.id, {
        maxDepth: 3,
        direction: 'both'
      });
      
      console.log('遍历路径:');
      traversalResult.forEach((node, index) => {
        console.log(`  ${index + 1}. ${node.name}`);
      });
    }

    console.log('\n✨ Demo 完成！DSL 已成功解析为内存中的 Domain Graph');
    
  } catch (error) {
    console.error('❌ 错误:', error);
    process.exit(1);
  }
}

// 运行 Demo
main().catch(console.error);

export { main };